package com.ccys.netty.controller;

import com.ccys.common.constants.TouristApi;
import com.ccys.common.vo.ResponseResult;
import com.ccys.netty.config.NettyConfig;
import com.ccys.netty.service.PushService;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import springfox.documentation.annotations.ApiIgnore;

import java.util.Map;
import java.util.Objects;
import java.util.concurrent.ConcurrentHashMap;


@RestController
@RequestMapping("/push")
public class PushController {

    @Autowired
    private PushService pushService;

    /**
     * 推送给所有用户
     * @param msg
     */
    @ApiIgnore
    @TouristApi
    @ApiOperation("websocket推送消息给所有用户(feign调用，忽略此接口)")
    @PostMapping("/sendMessageAllWebSocket")
    public ResponseResult sendMessageAllWebSocket(@RequestParam("msg") String msg){
        pushService.sendMessageAllWebSocket(msg);
        return ResponseResult.success();
    }
    /**
     * 推送给指定通道
     * @param objId （bookingID，用户ID）
     * @param msg
     */
    @ApiIgnore
    @TouristApi
    @ApiOperation("websocket推送消息给指定用户(feign调用，忽略此接口)")
    @PostMapping("sendMessageWebSocket")
    public ResponseResult sendMessageWebSocket(@RequestParam("objId") String objId, @RequestParam("msg") String msg){
        pushService.sendMessageWebSocket(objId,msg);
        return ResponseResult.success();
    }

    /**
     * 客户端发送消息给服务端（测试使用）
     * @param userId
     * @param msg
     */
    @ApiIgnore
    @TouristApi
    @ApiOperation("客户端webSocket发送消息给服务端（测试使用）(feign调用，忽略此接口)")
    @PostMapping("sendMessageWebSocketToServer")
    public ResponseResult sendMessageWebSocketToServer(@RequestParam("userId") String userId, @RequestParam("msg") String msg){
        ConcurrentHashMap<String, ChannelHandlerContext> userChannelMapaa = NettyConfig.getUserChannelMap();
        Map<String, Channel> userChannelMap = NettyConfig.getUserChannelMapClient();
        userChannelMap.put("aaa",null);
        Channel channel = userChannelMap.get(userId);
        if(!Objects.isNull(channel)){
            // 如果该用户的客户端是与本服务器建立的channel,直接推送消息
            //ChannelFuture channelFuture = channel.writeAndFlush(new TextWebSocketFrame(msg));
            ByteBuf bufff = Unpooled.buffer();
            bufff.writeBytes(msg.getBytes());
            channel.writeAndFlush(bufff);
        }
        return ResponseResult.success();
    }

}
